/**
 * Copyright 2010 Mark Wyszomierski
 */

package com.ruiyi.baseparser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import _test.Util;

import java.util.Iterator;

/**
 * Reference: http://www.json.org/javadoc/org/json/JSONObject.html
 * http://www.json.org/javadoc/org/json/JSONArray.html
 * 
 * @author Mark Wyszomierski (markww@gmail.com)
 * @param <T>
 */
@SuppressWarnings("rawtypes")
public class GroupParser extends AbstractParser<Group> {

	private Parser<? extends RuiyiType> mSubParser;

	public GroupParser(Parser<? extends RuiyiType> subParser) {
		mSubParser = subParser;
	}

	/**
	 * When we encounter a JSONObject in a GroupParser, we expect one attribute
	 * named 'type', and then another JSONArray attribute.
	 */
	@SuppressWarnings("unchecked")
	public Group<RuiyiType> parse(JSONObject json) throws JSONException {

		// if(Util.isResultPackage(json)){
		// return null;
		// }

		Group<RuiyiType> group = new Group<RuiyiType>();

		Iterator<String> it = (Iterator<String>) json.keys();
		while (it.hasNext()) {
			String key = it.next();
			// if (key.equals("type")) {
			// group.setType(json.getString(key));
			// } else {
			Object obj = json.get(key);
			if (obj instanceof JSONArray) {
				parse(group, (JSONArray) obj);
			} else {
				throw new JSONException("Could not parse data.");
			}
			// }
		}

		return group;
	}

	/**
	 * Here we are getting a straight JSONArray and do not expect the 'type'
	 * attribute.
	 */
	@Override
	public Group<RuiyiType> parse(JSONArray array) throws JSONException {

		Group<RuiyiType> group = new Group<RuiyiType>();
		parse(group, array);
		return group;
	}

	private void parse(Group<RuiyiType> group, JSONArray array)
			throws JSONException {
		for (int i = 0, m = array.length(); i < m; i++) {
			Object element = array.get(i);
			RuiyiType item = null;
			if (element instanceof JSONArray) {
				item = mSubParser.parse((JSONArray) element);
			} else {
				item = mSubParser.parse((JSONObject) element);
			}

			group.add(item);
		}
	}
}
